<template>
  <div class="oilGun-wrap">
    <div class="oilGun-table">
      <el-button @click="addOilGunVisible = true">新增</el-button>
      <el-table
        :data="tableData"
        stripe
        v-loading="showLoading"
        size="small"
        style="width: 100%">
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="100">
        </el-table-column>
        <el-table-column
          prop="gunNo"
          label="枪号"
          align="center">
        </el-table-column>
        <el-table-column
          prop="oilNoName"
          align="center"
          label="油号">
        </el-table-column>
        <el-table-column
          prop="checkStatus"
          align="center"
          label="审核状态">
          <template slot-scope="scope">
            <div>
              {{checkStatusList[scope.row.checkStatus]}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          align="center"
          label="状态">
          <template slot-scope="scope">
            <div>
              {{statusList[scope.row.status]}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作项"
          width="250">
          <template slot-scope="{row}">
            <div>
              <el-button class="table-mini-btn" v-if="row.status === 0" @click="showDialog('enableVisible', row)">开启</el-button>
              <el-button class="table-mini-btn" v-else @click="showDialog('disableVisible', row)">禁用</el-button>
              <el-button class="table-mini-btn" @click="modifyOilGun(row)">修改</el-button>
              <el-button class="table-mini-btn" @click="changeRecord(row)">变更记录</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="pageChange"
          :current-page="pagination.pageIndex"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 启用油枪 -->
    <el-dialog :visible.sync="enableVisible" width="400px" center>
      <div slot="title" class="dialog-title">启用油枪状态</div>
      <div>
        确定要开启油枪吗？
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="enableVisible = false">取 消</el-button>
        <el-button type="primary" @click="enableGasGun(true)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 禁用油枪 -->
     <el-dialog :visible.sync="disableVisible" width="400px" center>
      <div slot="title" class="dialog-title">禁用油枪状态</div>
      <div>
        禁用后，该油枪将不可使用，确定要禁止吗？
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="disableVisible = false">取 消</el-button>
        <el-button type="primary" @click="enableGasGun(false)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新建油枪 -->
    <el-dialog :visible.sync="addOilGunVisible" width="450px" center>
      <div slot="title" class="dialog-title">新建油枪</div>
      <el-form :model="oilGunInfo" ref="addOilGun" :inline="true" label-width="100px" :rules="addRules">
        <el-form-item label="油枪号：" prop="gunNo">
          <el-input v-model="oilGunInfo.gunNo" class="item-width" placeholder="请输入新创建的枪号，例如3" maxlength="3"></el-input>
        </el-form-item>
        <el-form-item label="油号：" prop="oilNo">
          <el-select v-model="oilGunInfo.oilNo" placeholder="请选择" class="item-width">
            <el-option v-for="item in oilNumList" :key="item.oilNo" :label="item.oilNum" :value="item.oilNo"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="(hideDialog('addOilGun'))">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="addOilGun">提 交</el-button>
      </span>
    </el-dialog>
    <!-- 修改油枪 -->
    <el-dialog :visible.sync="modifyOilGunVisible" width="450px" center>
      <div slot="title" class="dialog-title">修改油枪</div>
      <el-form :model="modifyOilGunInfo" ref="modifyOilGun" :inline="true" label-width="100px">
        <el-form-item label="油枪号：">
          <el-input v-model="modifyOilGunInfo.gunNo" class="item-width" disabled></el-input>
        </el-form-item>
        <el-form-item label="油号：">
          <el-select v-model="modifyOilGunInfo.oilNo" placeholder="请选择" class="item-width">
            <el-option v-for="item in oilNumList" :key="item.oilNo" :label="item.oilNum" :value="Number(item.oilNo)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="hideDialog('modifyOilGun')">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submit">提 交</el-button>
      </span>
    </el-dialog>
    <!-- 变更记录 -->
    <el-dialog :visible.sync="changeRecordVisible" center>
      <div slot="title" class="dialog-title">油枪变更记录</div>
      <el-table :data="changeRecordData" v-loading="showRecordLoading" size="small" stripe style="width: 100%">
        <el-table-column property="createUser" label="操作人" align="center"></el-table-column>
        <el-table-column property="createDt" label="操作时间" align="center"></el-table-column>
        <el-table-column property="operate" label="操作类型" align="center"></el-table-column>
        <el-table-column property="operateRecord" label="操作记录" align="center">
          <template slot-scope="{row}">
            <!-- <div v-if="row.beforeOilNo && row.afterOilNo">
              {{ `油号：由${row.beforeOilNo}改为：${row.afterOilNo}` }}
            </div> -->
            <span>{{ row.record }}</span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeRecordVisible = false">返 回</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { CHECKSTATUSLIST, STATUSLIST } from '@/config/gasStationManage'
import { getGasGunList, addGasGun, openGasGun, updateGasGun, oilGunLog, getOilNumList } from '@/api/gasStationManage/gasInfo'
import validate from '@/utils/validate'

export default {
  name: 'gasStationManage_gasGunManage',
  data () {
    return {
      tableData: [],
      pagination: {
        pageSize: 10,
        pageIndex: 1
      },
      total: 0,
      loading: false,
      checkStatusList: CHECKSTATUSLIST,
      statusList: STATUSLIST,
      enableVisible: false,
      disableVisible: false,
      addOilGunVisible: false,
      modifyOilGunVisible: false,
      changeRecordVisible: false,
      showLoading: false,
      showRecordLoading: false,
      oilGunInfo: { // 油枪信息
        gunNo: '',
        oilNo: '',
        // oilNum: ''
      },
      modifyOilGunInfo: {
        id: '',
        gunNo: '',
        oilNo: '',
        oilNum: ''
      },
      oilNumList: [],
      changeRecordData: [], // 变更记录
      addRules: { // 新增油枪弹框输入校验
        gunNo: [{required: true, validator: validate.validateGunNo, trigger: 'blur'}],
        oilNo: [{required: true, message: '请选择油号'}]
      },
      changeId: null, // 禁用/启用的油枪ID
      submitLoading: false
    }
  },
  methods: {
    async initTable () {
      this.showLoading = true
      try {
        const { code, result = [], totalRow } = await getGasGunList(this.pagination)
        if (code !== 200) return
        this.tableData = result
        this.total = totalRow
      } catch (err) {
        console.log(err)
      } finally {
        this.showLoading = false
      }
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.initTable()
    },
    pageChange (val) {
      this.pagination.pageIndex = val
      this.initTable()
    },
    // 新增油枪
    addOilGun () {
      this.$refs.addOilGun.validate(async (valid) => {
        if (!valid) return
        try {
          this.submitLoading = true
          const { code } = await addGasGun(this.oilGunInfo)
          if (code !== 200) return
          this.$message.success('新增成功')
          this.hideDialog('addOilGun')
          this.initTable()
        } catch (error) {
          console.log(error)
        } finally {
          this.submitLoading = false
        }
      })
    },
    /**
     * @description 启/禁用油枪
     * @param {type} true 为启用 false 为禁用
     */
    async enableGasGun (type) {
      try {
        const {code } = await openGasGun({isOpen: type, id: this.changeId})
        if (code === 200) {
          this.$message.success(`${type ? '启用' : '禁用'}成功`)
          this.initTable()
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.enableVisible = false
        this.disableVisible = false
      }
    },
    // 修改油枪
    async modifyOilGun (row) {
      Object.assign(this.modifyOilGunInfo, row)
      this.modifyOilGunVisible = true
    },
    // 提交修改
    async submit () {
      const {id, gunNo ,oilNo, gasId} = this.modifyOilGunInfo
      const params = {id, oilNo, gasId, gunNo}
      try {
        this.submitLoading = true
        const {code} = await updateGasGun(params)
        if (code !== 200) return
        this.$message.success('修改成功')
        this.initTable()
      } catch (err) {
        console.log(err)
      } finally {
        this.submitLoading = false
        this.modifyOilGunVisible = false
      }
    },
    // 变更记录
    async changeRecord (row) {
      this.changeRecordVisible = true
      this.showRecordLoading = true
      try {
        const {code, result} = await oilGunLog({gasId: row.gasId, gunNo: row.gunNo})
        if (code !== 200) return
        this.changeRecordData = result
      } catch (err) {
        console.log(err)
      } finally {
        this.showRecordLoading = false
      }
    },
    // 显示禁用/启用油站弹框
    showDialog (popName, row) {
      this[popName] = true
      this.changeId = row.id
    },
    // 隐藏新增和修改弹框并重置
    hideDialog (formName) {
      this[formName + 'Visible'] = false
      this.$refs[formName].resetFields()
    }
  },
  // watch: {
  //   'oilGunInfo.oilNo': {
  //     deep: true,
  //     handler (val) {
  //       this.oilNumList.map(item => {
  //         if (item.oilNo === val) {
  //           this.oilGunInfo.oilNum = item.oilNum
  //         }
  //       })
  //     }
  //   }
  // },
  async created () {
    this.initTable()
    try {
      const {code, result} = await getOilNumList()
      if (code !== 200) return
      this.oilNumList = Object.entries(result).map(item => {
        return {
          oilNo: item[0],
          oilNum: item[1]
        }
      })
    } catch (err) {
      console.log(err)
    }
  }
}
</script>
<style lang="less" scoped>
  @import url('../mixin.less');

  .oilGun-table {
    & > .el-button {
      width:120px;
      height:30px;
      line-height: 30px;
      margin: 30px 20px;
      background:rgba(255,255,255,1);
      border-radius:2px;
      border:1px solid rgba(75,126,254,1);
      padding: 0;
      font-size: 14px;
      color:rgba(75,126,254,1);
    }
    .pagination {
      margin-top: 20px;
      float: right;
    }
  }
  .item-width {
    width: 250px;
  }
</style>